package com.github.wxiaoqi.security.biz.codex.api;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.biz.codex.biz.MarCouponBiz;
import com.github.wxiaoqi.security.biz.codex.biz.MarRandomCouponBiz;
import com.github.wxiaoqi.security.biz.codex.biz.MarRandomCouponLevelBiz;
import com.github.wxiaoqi.security.biz.codex.entity.MarCoupon;
import com.github.wxiaoqi.security.biz.codex.entity.MarRandomCoupon;
import com.github.wxiaoqi.security.biz.codex.entity.MarRandomCouponLevel;
import com.github.wxiaoqi.security.biz.util.NumberUtils;
import com.github.wxiaoqi.security.biz.util.RedEnvelopUtil;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.SerialNoUtil;


/**
 * 红包管理
 * @author Administrator
 *
 */
@Controller
@RequestMapping("coupon")
public class CouponApi  extends BaseController<MarCouponBiz, MarCoupon> {

	private final Logger logger = LoggerFactory.getLogger(CouponApi.class);
	
	@Autowired
	private MarCouponBiz couponInfoBiz;
	@Autowired 
	private MarRandomCouponLevelBiz couponLevelBiz;
	@Autowired
	private MarRandomCouponBiz randomCouponBiz;
    @Autowired
    private UserAuthUtil userAuthUtil;
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public ObjectRestResponse<MarCoupon> addCouponInfo(@RequestBody Map<String, Object> params) throws ParseException {
		logger.info("添加红包。。。{} "+params);
		MarCoupon coupon = new MarCoupon();
		//活动编号
		String actId = "";
		if (StringUtils.isNotEmpty((String) params.get("actId"))) {
			actId = (String) params.get("actId");
		}
		//优惠券批次号
		String couId = SerialNoUtil.createID();
		//优惠券开始时间
		String startTime = "";
		//优惠券到期时间
		String endTime = "";
		//红包类型
		String couType = (String) params.get("couType");
		//领取方式 01自动领取 02手动领取
		String payment = "";
		//红包数量
		String couAmt = "";
		//随机红包金额
		String couSum = "";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
		DateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//创建时间
		try {
			coupon.setCreateTime(sdf1.parse(sdf1.format(new Date())));
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		//红包状态，00可领，01不可领
		String couStatus = "";
		if (StringUtils.isNotEmpty((String) params.get("couStatus"))) {
			couStatus = (String) params.get("couStatus");
			couStatus = couponInfoBiz.getCouStatus(actId,couStatus);
		}
		if ("1".equals(couType)) {
			//随机红包
			payment = "02";
			Integer firstCount = Integer.valueOf((String)params.get("oneCount"));
			Integer secondCount = Integer.valueOf((String)params.get("twoCount"));
			Integer thirdCount = Integer.valueOf((String)params.get("threeCount"));
			couAmt = String.valueOf(firstCount+secondCount+thirdCount);
			float firstAmt = Float.valueOf((String) params.get("oneAmt"));
			float oneMax = Float.valueOf((String) params.get("oneMax"));
			float oneMin = Float.valueOf((String) params.get("oneMin"));
			float secondAmt = Float.valueOf((String) params.get("twoAmt"));
			float twoMax = Float.valueOf((String) params.get("twoMax"));
			float twoMin = Float.valueOf((String) params.get("twoMin"));
			float thirdAmt = Float.valueOf((String) params.get("threeAmt"));
			float threeMax = Float.valueOf((String) params.get("threeMax"));
			float threeMin = Float.valueOf((String) params.get("threeMin"));
			couSum = String.valueOf(firstAmt+secondAmt+thirdAmt);
			coupon.setCouSum(new BigDecimal(couSum));
			//添加等级
			addRandomCouponLevel(couId, new BigDecimal(firstAmt), firstCount, new BigDecimal(secondAmt), secondCount, new BigDecimal(thirdAmt), thirdCount);
			//添加随机红包
			addRandomCoupon(couId, couStatus, firstAmt, firstCount,oneMax,oneMin, secondAmt, secondCount,twoMax,twoMin, thirdAmt, thirdCount,threeMax,threeMin);
		}else {
			if (StringUtils.isNotEmpty((String) params.get("payment"))) {
				payment = (String) params.get("payment");
			}
			try {
				if (StringUtils.isNotEmpty((String) params.get("startTime"))) {
					startTime = (String) params.get("startTime");
					startTime = startTime.replace("Z", " UTC");
					System.out.println("开始时间："+format.parse(startTime));
					coupon.setStartTime(format.parse(startTime));
				}
				if (StringUtils.isNotEmpty((String) params.get("endTime"))) {
					endTime = (String) params.get("endTime");
					endTime = endTime.replace("Z", " UTC");
					Date rEnd = format.parse(endTime);
					Calendar c = Calendar.getInstance();
					c.setTime(rEnd);
					c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
					Date endD = c.getTime();
					System.out.println("结束时间："+endD);
					coupon.setEndTime(endD);				} 
			}catch (ParseException e) {
					e.printStackTrace();
			}
			if (StringUtils.isNotEmpty((String) params.get("couAmt"))) {
				couAmt = (String) params.get("couAmt");
			}
		}
		//优惠券说明
		String couInfo = (String) params.get("couInfo");
		//优惠券名
		String couName = (String) params.get("couName");
		//每天限领次数
		Integer everyDay = 0;
		if (StringUtils.isNotEmpty((String) params.get("everyDay"))) {
			everyDay = Integer.valueOf((String) params.get("everyDay"));
		}
		//每月限领次数
		Integer everyMonth = 0;
		if (StringUtils.isNotEmpty((String) params.get("everyMonth"))) {
			everyMonth = Integer.valueOf((String) params.get("everyMonth"));
		}
		//每周限领次数
		Integer everyWeek = 0;
		if (StringUtils.isNotEmpty((String) params.get("everyWeek"))) {
			everyWeek = Integer.valueOf((String) params.get("everyWeek"));
		}
		//事件编码 多个事件用逗号分隔
		String incCode = "";
		if (StringUtils.isNotEmpty((String) params.get("incCode"))) {
			incCode = (String) params.get("incCode");
		}
		//领取结束时间
		String revEnd = "";
		if (StringUtils.isNotEmpty((String) params.get("revEnd"))) {
			revEnd = (String) params.get("revEnd");
			revEnd = revEnd.replace("Z", " UTC");
			Date rEnd = format.parse(revEnd);
			Calendar c = Calendar.getInstance();
			c.setTime(rEnd);
			c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
			Date endD = c.getTime();
			System.out.println("领取结束时间："+endD);
			coupon.setRevEnd(endD);
		}
		//红包领取开始时间
		String revStart = "";
		if (StringUtils.isNotEmpty((String) params.get("revStart"))) {
			revStart = (String) params.get("revStart");
			revStart = revStart.replace("Z", " UTC");
			System.out.println("领取开始时间："+format.parse(revStart));
			coupon.setRevStart(format.parse(revStart));
		}
		//场景编号
		String sceneId = "";
		if (StringUtils.isNotEmpty((String) params.get("sceneId"))) {
			sceneId = (String) params.get("sceneId");
			coupon.setSceneId(sceneId);
		}
		//优惠券抵扣金额
		if (StringUtils.isNotEmpty((String) params.get("subtraction"))) {
			BigDecimal subtraction = new BigDecimal((String) params.get("subtraction"));
			coupon.setSubtraction(subtraction);
		}
		//使用红包最低金额
		if (StringUtils.isNotEmpty((String) params.get("totalPay"))) {
			BigDecimal totalPay = new BigDecimal((String) params.get("totalPay"));
			coupon.setTotalPay(totalPay);
		}
		String authToken = (String) params.get("actToken");
		try {
			IJWTInfo info =	userAuthUtil.getInfoFromToken(authToken);
			coupon.setCreatUser(info.getXId());
		} catch (Exception e) {
			logger.info("未获取到当前用户");
			e.printStackTrace();
		}
		coupon.setActId(actId);
		coupon.setCouAmt(Integer.valueOf(couAmt));
		coupon.setCouId(couId);
		coupon.setCouInfo(couInfo);
		coupon.setCouName(couName);
		coupon.setCouStatus(couStatus);
		coupon.setEveryDay(everyDay);
		coupon.setEveryMonth(everyMonth);
		coupon.setEveryWeek(everyWeek);
		coupon.setIncCode(incCode);
		coupon.setPayment(payment);
		coupon.setCouType(couType);
		logger.info("添加红包。。。{}"+coupon);
		couponInfoBiz.insertSelective(coupon);
		logger.info("添加红包结束。。。");
		return new ObjectRestResponse<MarCoupon>();
	}
	
	@ResponseBody
	@RequestMapping(value = "/info", method = RequestMethod.POST)
	public ObjectRestResponse<MarCoupon> getCouponInfo(@RequestBody Map<String, Object> params) {
		logger.info("查询红包信息。。。{}"+params);
		ObjectRestResponse<MarCoupon> objectRestResponse = new ObjectRestResponse<>();
		String couId =(String)params.get("couId") ;
		MarCoupon coupon = couponInfoBiz.selectBycouId(couId);
		objectRestResponse.data(coupon);
		return objectRestResponse;
	}
	@ResponseBody
	@RequestMapping(value = "/close", method = RequestMethod.POST)
	public ObjectRestResponse<MarCoupon> closeCoupon(@RequestBody Map<String, Object> params) {
		logger.info("停用红包。。。{}"+params);
		String  couId =(String)params.get("couId") ;
		MarCoupon coupon = couponInfoBiz.selectBycouId(couId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		coupon.setCouStatus("01");
		try {
			coupon.setShutTime(sdf.parse(sdf.format(new Date())));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		couponInfoBiz.updateSelectiveById(coupon);
		return new ObjectRestResponse<MarCoupon>();
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ObjectRestResponse<MarCoupon> updateCouponInfo(@RequestBody Map<String, Object> params) {
		logger.info("修改红包。。。{}"+params);
		String  couId =(String)params.get("couId") ;
		MarCoupon coupon = couponInfoBiz.selectBycouId(couId);
		String couName = (String) params.get("couName");
		String totalPay =  String.valueOf(params.get("totalPay"));
		if (StringUtils.isEmpty(totalPay)) {
			totalPay = "0";
		}
		String subtraction = String.valueOf(params.get("subtraction"));
		if (StringUtils.isEmpty(subtraction)) {
			subtraction = "0";
		}
		String startTime = (String) params.get("startTime");
		String endTime = (String) params.get("endTime");
		String couStatus = (String) params.get("couStatus");
		couStatus = couponInfoBiz.getUpCouStatus(couId,couStatus);
		coupon.setCouStatus(couStatus);
		String revStart = (String) params.get("revStart");
		String revEnd = (String) params.get("revEnd");
		String sceneId = (String) params.get("sceneId");
		String payment = (String) params.get("payment");
		
		if (StringUtils.isNotEmpty(String.valueOf((Integer) params.get("everyDay")))) {
			Integer everyDayStr = Integer.valueOf(params.get("everyDay").toString());
			coupon.setEveryDay(everyDayStr);
		}
		if (StringUtils.isNotEmpty(String.valueOf((Integer) params.get("everyWeek")))) {
			Integer everyWeekStr = Integer.valueOf(params.get("everyWeek").toString());
			coupon.setEveryWeek(everyWeekStr);
		}
		if (StringUtils.isNotEmpty(String.valueOf((Integer) params.get("everyMonth")))) {
			Integer everyMonthStr = Integer.valueOf(params.get("everyMonth").toString());
			coupon.setEveryMonth(everyMonthStr);
		}
		if (StringUtils.isNotEmpty((String) params.get("incCode"))) {
			String incCode = (String) params.get("incCode");
			coupon.setIncCode(incCode);
		}
		if (StringUtils.isNotEmpty((String) params.get("couInfo"))) {
			String couInfo = (String) params.get("couInfo");
			coupon.setCouInfo(couInfo);
		}
		Integer couAmtStr = Integer.valueOf(params.get("couAmt").toString());
		coupon.setCouAmt(couAmtStr);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		coupon.setCouName(couName);
		coupon.setTotalPay(new BigDecimal(totalPay));
		coupon.setSubtraction(new BigDecimal(subtraction));
		try {
			coupon.setShutTime(sdf.parse(sdf.format(new Date())));
			coupon.setStartTime(new Date(sdf1.parse(startTime).getTime()));
			coupon.setEndTime(new Date(sdf1.parse(endTime).getTime()));
			coupon.setRevStart(new Date(sdf1.parse(revStart).getTime()));
			coupon.setRevEnd(new Date(sdf1.parse(revEnd).getTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		coupon.setSceneId(sceneId);
		coupon.setPayment(payment);
		couponInfoBiz.updateSelectiveById(coupon);
		logger.info("红包修改结束。。。");
		return new ObjectRestResponse<MarCoupon>();
	}
	
	/**
	 * 根据活动编号，红包领取时间查询红包列表
	 * @param params
	 * @return
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value = "/page", method = RequestMethod.POST)
	public TableResultResponse<MarCoupon> getCouponList(@RequestParam("page") String page, @RequestParam("limit") String limit, String actId, String revStart, String revEnd, String couType) throws ParseException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", page);
		params.put("limit", limit);
		if(StringUtils.isNotBlank(actId)){   
			params.put("actId", actId);
		}
		if (StringUtils.isNotBlank(couType)) {
			params.put("couType", couType);
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
		if(!StringUtils.isEmpty(revStart)){
			revStart  = revStart.replace("Z", " UTC");
			Date rStart = format.parse(revStart);
			params.put("revStart", sdf.format(rStart));
		}
		if(!StringUtils.isEmpty(revEnd)){
			revEnd = revEnd.replace("Z", " UTC");
			Date rEnd = format.parse(revEnd);
			Calendar c = Calendar.getInstance();
		    c.setTime(rEnd);
		    c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
		    Date endD = c.getTime();
			params.put("revEnd", sdf.format(endD));
		}
		logger.info("查询红包列表。。。{}"+params);
		Query query = new Query(params);
		Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
		List<MarCoupon> list = couponInfoBiz.getCouponList(params);
		return new TableResultResponse<MarCoupon>(result.getTotal(), list);
	}
	
	
	/**
	 * 添加红包档
	 * @param couId
	 * @param firstAmt
	 * @param firstCount
	 * @param secondAmt
	 * @param secondCount
	 * @param thirdAmt
	 * @param thirdCount
	 */
	public void addRandomCouponLevel(String couId, BigDecimal firstAmt, Integer firstCount, BigDecimal secondAmt, Integer secondCount, BigDecimal thirdAmt, Integer thirdCount) {
		logger.info("添加红包档。。。");
		MarRandomCouponLevel couponLevel = new MarRandomCouponLevel();
		couponLevel.setCouId(couId);
		couponLevel.setFirstAmt(firstAmt);
		couponLevel.setFirstCount(firstCount);
		couponLevel.setSecondAmt(secondAmt);
		couponLevel.setSecondCount(secondCount);
		couponLevel.setThirdAmt(thirdAmt);
		couponLevel.setThirdCount(thirdCount);
		couponLevelBiz.insertSelective(couponLevel);
		logger.info("添加红包档...结束");
	}
	
	/**
	 * 产生随机红包
	 * @param couId
	 * @param couStatus
	 * @param level
	 * @param amt
	 * @param count
	 * @param max
	 * @param min
	 */
	public void addRandomCoupon(String couId, String couStatus, double firstAmt, Integer firstCount,double oneMax, double oneMin, double secondAmt, Integer secondCount,double twoMax, double twoMin, double thirdAmt, Integer thirdCount,double threeMax, double threeMin) {
		logger.info("添加随机红包。。。{}");
		List<MarRandomCoupon> list = new ArrayList<>();
		long startTime1=System.currentTimeMillis();
		double[] first = RedEnvelopUtil.generate(firstAmt, firstCount, oneMax, oneMin);
		if (first != null && first.length > 0) {
			for (double d : first) {
				MarRandomCoupon randomCoupon = new MarRandomCoupon();
				String coupSerial = NumberUtils.generateSerialNumber();
				randomCoupon.setCouId(couId);
				randomCoupon.setCouSerial(coupSerial);
				randomCoupon.setCouAmt(new BigDecimal(d));
				randomCoupon.setCouLevel("01");
				randomCoupon.setRevStatus(couStatus);
				randomCoupon.setIsReceived("00");
				DateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					randomCoupon.setCreteTime(sdf1.parse(sdf1.format(new Date())));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				list.add(randomCoupon);
			}
		}
		long endTime1=System.currentTimeMillis();
		System.out.println("1级耗时："+(endTime1-startTime1)+"ms");
		long startTime2=System.currentTimeMillis();
		double[] second = RedEnvelopUtil.generate(secondAmt, secondCount, twoMax, twoMin);
		if (second != null && second.length > 0) {
			for (double d : second) {
				MarRandomCoupon randomCoupon = new MarRandomCoupon();
				String coupSerial = NumberUtils.generateSerialNumber();
				randomCoupon.setCouId(couId);
				randomCoupon.setCouSerial(coupSerial);
				randomCoupon.setCouAmt(new BigDecimal(d));
				randomCoupon.setCouLevel("02");
				randomCoupon.setRevStatus(couStatus);
				randomCoupon.setIsReceived("00");
				DateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					randomCoupon.setCreteTime(sdf1.parse(sdf1.format(new Date())));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				list.add(randomCoupon);
			}
		}
		long endTime2=System.currentTimeMillis();
		System.out.println("2级耗时："+(endTime2-startTime2)+"ms");
		long startTime3=System.currentTimeMillis();
		double[] third = RedEnvelopUtil.generate(thirdAmt, thirdCount, threeMax, threeMin);
		if (third != null && third.length > 0) {
			for (double d : third) {
				MarRandomCoupon randomCoupon = new MarRandomCoupon();
				String coupSerial = NumberUtils.generateSerialNumber();
				randomCoupon.setCouId(couId);
				randomCoupon.setCouSerial(coupSerial);
				randomCoupon.setCouAmt(new BigDecimal(d));
				randomCoupon.setCouLevel("03");
				randomCoupon.setRevStatus(couStatus);
				randomCoupon.setIsReceived("00");
				DateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					randomCoupon.setCreteTime(sdf1.parse(sdf1.format(new Date())));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				list.add(randomCoupon);
			}
		} 
		long endTime3=System.currentTimeMillis();
		System.out.println("3级耗时："+(endTime3-startTime3)+"ms");
		long startTime4=System.currentTimeMillis();
		if (list != null && list.size() > 0) {
			int pointsDataLimit = 1000;//限制条数
			Integer size = list.size();
			if (size > pointsDataLimit) {
				int part = size/pointsDataLimit;
				System.out.println("共有 ： "+size+"条，！"+" 分为 ："+part+"批");
				for(int i = 0;i < part;i++) {
					List<MarRandomCoupon> listPage = list.subList(0, pointsDataLimit);
					randomCouponBiz.addRandomCouponList(listPage);
					list.subList(0, pointsDataLimit).clear();
				}
				if (!list.isEmpty()) {
					randomCouponBiz.addRandomCouponList(list);
				}
			}else {
				randomCouponBiz.addRandomCouponList(list);
			}
		}
		long endTime4=System.currentTimeMillis();
		System.out.println("插入耗时："+(endTime4-startTime4)+"ms");
		logger.info("添加随机红包结束。。。{}");
	}
	
}
